const db = require('../db/connMysql');
const mysql_tool = require('../util/mysql_tool');
const minio = require('../db/connMinio');


const sickenDao = {
    /*
     * 新增病例档案接口
     */
    async addSickenRecord(studentId, time, hospital, sickenTypeId, note, photoUrl) {
        let isRollback = false;
        let result = await new Promise((resolve, reject) => {
            db.getConnection(async (err, connection) => {
                try {
                    if (err) {
                        // 连不上数据库
                        connection.release();
                        reject(err);
                        return ;
                    }
    
                    // 开启事务
                    let start_transaction = await mysql_tool.mysqlTransation(connection);
                    if (start_transaction.success == false) {
                        reject(start_transaction.err);
                        return ;
                    }
    
                    // 创建病例档案
                    let sql1 = `insert into MedicalRecords(
                                   studentId, time, hospital, illTypeId, note, photoUrl
                               ) VALUES (?, ?, ?, ?, ?, "")`;
                    let data1 = [studentId, time, hospital, sickenTypeId, note];
                    let create_sicken = await mysql_tool.execSqlInTransaction(connection, sql1, data1);
                    if (create_sicken.success == false) {
                        reject(create_sicken.err);
                        return ;
                    }
                    create_sicken = create_sicken.result;
                    let insertId = create_sicken.insertId;

                    // 提取 base64 数据部分
                    let base64Data = photoUrl.split(',')[1];
                    // 将 base64 数据转换为 Buffer
                    let buffer = Buffer.from(base64Data, 'base64');
                    // 定义 MinIO 的 bucket 名称和对象名称
                    let bucketName = 'public'; // 替换为你的 bucket 名称
                    let objectName = `MedicalRecords-${insertId}.png`; // 替换为你希望在 MinIO 中存储的对象名称

                    // 上传 Buffer 到 MinIO
                    await minio.minio.putObject(bucketName, objectName, buffer, buffer.length, async function (err, etag) {
                        if (err) {
                            await mysql_tool.rollbackTransaction(connection);
                            isRollback = true;
                            reject(err);
                            return ;
                        }
                    });

                    // 插入到 publicimg中
                    let sql2 = `INSERT INTO PublicImg(
                            browser, uri, status
                        ) VALUES (?, ?, ?)`;
                    let data2 = [bucketName, objectName, '已完成'];
                    let result2 = await mysql_tool.execSqlInTransaction(connection, sql2, data2);
                    let imgId = result2.result.insertId;

                    // 更新imgId到病例档案中
                    let sql3 = `UPDATE MedicalRecords SET imgId = ? WHERE medicalId = ?`;
                    let data3 = [imgId, insertId];
                    await mysql_tool.execSqlInTransaction(connection, sql3, data3);
    
                    // 提交事务
                    if (!isRollback) {
                        // 返回结果
                        await mysql_tool.commitTransaction(connection);
                        resolve(create_sicken);
                    }
                } catch (err) {
                    console.log('【上传图片接口报错】', err);
                    reject(err);
                }
            });
        });
        return result;
    },
    async addSickenRecordNoImg(studentId, time, hospital, sickenTypeId, note) {
        // 创建病例档案
        let sql = `insert into MedicalRecords(
            studentId, time, hospital, illTypeId, note, photoUrl
        ) VALUES (?, ?, ?, ?, ?, "")`;
        let data = [studentId, time, hospital, sickenTypeId, note];
        return mysql_tool.execSql(sql, data);
    },
    /*
     * 获取所有病例类型
     */
    async getAllSickenType() {
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                let sql = `select * from IllTypes`;
                connection.query(sql, [], function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;
    },
    /*
     * 查询某个学生的所有病例档案接口
     */
    async getSickenRecordByStudent(uid, studentId) {
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                let sql = `select
                        medicalId,
                        studentId,
                        time,
                        hospital,
                        illTypeId,
                        note,
                        imgId
                    from MedicalRecords where studentId = ?`;
                connection.query(sql, [studentId], function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;
    },
};

module.exports = sickenDao;